<template>
	<view class="cart-container">
		<!-- 购物车为空时显示 -->
		<view v-if="!cartItems || cartItems.length === 0" class="empty-cart">
			<image src="/static/empty-cart.png" mode="aspectFit" class="empty-image"></image>
			<text class="empty-text">购物车还是空的</text>
			<button class="go-shopping-btn" @tap="goShopping">去逛逛</button>
		</view>

		<!-- 购物车列表 -->
		<view v-else class="cart-list">
			<view v-for="(item, index) in cartItems" :key="index" class="cart-item">
				<view class="item-left">
					<checkbox :checked="item.selected" @tap="toggleItemSelection(index)" color="#007AFF" />
				</view>
				<view class="item-content" @tap="goToDetail(item)">
					<image :src="item.image" mode="aspectFill" class="item-image"></image>
					<view class="item-info">
						<text class="item-name">{{ item.name }}</text>
						<text class="item-price">¥{{ item.price }}</text>
					</view>
				</view>
				<view class="item-right">
					<view class="quantity-control">
						<text class="quantity-btn" @tap="updateItemCount(index, -1)">-</text>
						<text class="quantity">{{ item.quantity || 1 }}</text>
						<text class="quantity-btn" @tap="updateItemCount(index, 1)">+</text>
					</view>
					<text class="delete-btn" @tap="removeItem(index)">删除</text>
				</view>
			</view>
		</view>

		<!-- 底部结算栏 -->
		<view class="cart-footer">
			<view class="footer-left">
				<checkbox :checked="isAllSelected" @tap="toggleAllSelection" color="#007AFF" />
				<text>全选</text>
			</view>
			<view class="footer-right">
				<view class="total-info">
					<text>合计：</text>
					<text class="total-price">¥{{ totalPrice }}</text>
				</view>
				<button class="checkout-button" :disabled="!hasSelectedItems" @tap="checkout">
					结算({{ totalCount }})
				</button>
			</view>
		</view>
	</view>
</template>

<script>
import { ref, computed } from 'vue'

export default {
	data() {
		return {
			cartItems: [],
			userInfo: null,
			balance: 0
		}
	},
	computed: {
		// 是否全选
		isAllSelected() {
			return this.cartItems.length > 0 && this.cartItems.every(item => item.selected)
		},
		// 是否有选中的商品
		hasSelectedItems() {
			return this.cartItems.some(item => item.selected)
		},
		// 总价格
		totalPrice() {
			return this.cartItems
				.filter(item => item.selected)
				.reduce((total, item) => {
					const price = parseFloat(item.price) || 0
					const quantity = parseInt(item.quantity) || 1
					return total + (price * quantity)
				}, 0)
				.toFixed(2)
		},
		// 总数量
		totalCount() {
			return this.cartItems
				.filter(item => item.selected)
				.reduce((total, item) => total + (parseInt(item.quantity) || 1), 0)
		}
	},
	methods: {
		// 加载购物车数据
		async loadCartItems() {
			try {
				if (!this.userInfo) {
					console.log('用户未登录，尝试重新加载用户信息') // 调试日志
					await this.loadUserInfo()
				}

				if (!this.userInfo) {
					console.log('用户未登录，无法加载购物车数据') // 调试日志
					return
				}

				const userList = uni.getStorageSync('userList') || []
				const currentUser = userList.find(item => item.uid === this.userInfo.uid)
				
				if (currentUser && currentUser.cart) {
					this.cartItems = currentUser.cart.map(item => ({
						...item,
						selected: false,
						quantity: item.quantity || 1
					}))
					console.log('加载的购物车数据:', this.cartItems) // 调试日志
				} else {
					console.log('未找到购物车数据') // 调试日志
					this.cartItems = []
				}
			} catch (error) {
				console.error('加载购物车数据失败:', error)
				this.cartItems = []
			}
		},

		// 结算
		async checkout() {
			if (!this.hasSelectedItems) {
				uni.showToast({
					title: '请选择商品',
					icon: 'none'
				})
				return
			}

			// 检查用户信息
			const userInfo = uni.getStorageSync('userInfo')
			if (!userInfo) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}, 1500)
				return
			}

			// 获取用户列表
			const userList = uni.getStorageSync('userList') || []
			const userIndex = userList.findIndex(item => item.uid === JSON.parse(userInfo).uid)
			
			if (userIndex === -1) {
				uni.showToast({
					title: '用户信息不存在',
					icon: 'none'
				})
				return
			}

			// 检查余额
			const userBalance = parseFloat(userList[userIndex].balance)
			const totalPrice = parseFloat(this.totalPrice)
			
			if (userBalance < totalPrice) {
				uni.showModal({
					title: '余额不足',
					content: `您的余额为¥${userBalance}，需要支付¥${totalPrice}，是否前往充值？`,
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/money/money'
							})
						}
					}
				})
				return
			}

			// 创建订单
			try {
				const selectedItems = this.cartItems.filter(item => item.selected)
				const orderData = {
					id: Date.now().toString(),
					items: selectedItems.map(item => ({
						productId: item.id,
						quantity: parseInt(item.quantity) || 1,
						price: parseFloat(item.price) || 0,
						name: item.name,
						image: item.image,
						totalPrice: (parseFloat(item.price) || 0) * (parseInt(item.quantity) || 1)
					})),
					totalAmount: totalPrice,
					orderTime: new Date().toISOString(),
					status: 'paid' // 直接设置为已支付状态
				}

				console.log('订单数据:', orderData) // 调试日志

				// 更新用户余额
				userList[userIndex].balance = (userBalance - totalPrice).toFixed(2)
				
				// 添加订单到用户订单列表
				const orders = userList[userIndex].orders || []
				orders.unshift(orderData)
				userList[userIndex].orders = orders
				
				// 从购物车中移除已购买的商品
				const remainingItems = this.cartItems.filter(item => !item.selected)
				userList[userIndex].cart = remainingItems
				
				// 保存更新后的用户列表
				uni.setStorageSync('userList', userList)
				
				// 更新当前页面的购物车数据
				this.cartItems = remainingItems
				
				// 更新余额显示
				this.balance = userList[userIndex].balance

				uni.showToast({
					title: '购买成功',
					icon: 'success'
				})

				// 延迟跳转到订单页面
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/order/order'
					})
				}, 1500)
			} catch (error) {
				console.error('创建订单失败:', error)
				uni.showToast({
					title: '创建订单失败，请稍后重试',
					icon: 'none'
				})
			}
		},

		// 去购物
		goShopping() {
			uni.switchTab({
				url: '/pages/index/index'
			})
		},

		// 跳转到商品详情
		goToDetail(item) {
			uni.navigateTo({
				url: `/pages/detail/detail?id=${item.id}`
			})
		},

		// 加载用户信息
		async loadUserInfo() {
			try {
				// 从本地存储获取用户信息
				const userInfo = uni.getStorageSync('userInfo')
				console.log('获取到的用户信息:', userInfo) // 调试日志
				
				if (userInfo) {
					this.userInfo = JSON.parse(userInfo)
					console.log('解析后的用户信息:', this.userInfo) // 调试日志
					
					// 获取用户余额
					const userList = uni.getStorageSync('userList') || []
					const currentUser = userList.find(item => item.uid === this.userInfo.uid)
					
					if (currentUser) {
						this.balance = currentUser.balance || 0
						console.log('用户余额:', this.balance) // 调试日志
					}
				} else {
					console.log('未找到用户信息') // 调试日志
					// 如果未登录，跳转到登录页面
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}, 1500)
				}
			} catch (error) {
				console.error('加载用户信息失败:', error)
				this.userInfo = null
				this.balance = 0
			}
		},

		// 更新选择状态
		updateSelection() {
			console.log('更新选择状态，当前购物车数据：', this.cartItems)
			if (!this.cartItems || this.cartItems.length === 0) {
				this.isAllSelected = false
				this.totalCount = 0
				this.totalPrice = '0.00'
				return
			}
			
			// 更新全选状态
			this.isAllSelected = this.cartItems.every(item => item.selected)
			console.log('全选状态：', this.isAllSelected)
			
			// 更新总价和数量
			const selectedItems = this.cartItems.filter(item => item.selected)
			console.log('选中的商品：', selectedItems)
			this.totalCount = selectedItems.reduce((sum, item) => sum + (item.quantity || 1), 0)
			this.totalPrice = selectedItems.reduce((sum, item) => sum + item.price * (item.quantity || 1), 0).toFixed(2)
			console.log('总数量：', this.totalCount, '总价格：', this.totalPrice)
		},

		// 切换单个商品选择状态
		toggleItemSelection(index) {
			this.cartItems[index].selected = !this.cartItems[index].selected
			this.updateSelection()
			this.saveCartData()
		},

		// 切换全选状态
		toggleAllSelection() {
			this.isAllSelected = !this.isAllSelected
			this.cartItems.forEach(item => {
				item.selected = this.isAllSelected
			})
			this.updateSelection()
			this.saveCartData()
		},

		// 更新商品数量
		updateItemCount(index, delta) {
			const item = this.cartItems[index]
			const newQuantity = (item.quantity || 1) + delta
			if (newQuantity > 0) {
				item.quantity = newQuantity
				this.updateSelection()
				this.saveCartData()
			}
		},

		// 删除商品
		removeItem(index) {
			uni.showModal({
				title: '提示',
				content: '确定要删除这个商品吗？',
				success: (res) => {
					if (res.confirm) {
						this.cartItems.splice(index, 1)
						this.updateSelection()
						this.saveCartData()
					}
				}
			})
		},

		// 保存购物车数据
		saveCartData() {
			try {
				if (!this.userInfo) {
					console.log('用户未登录，无法保存购物车数据') // 调试日志
					return
				}

				const userList = uni.getStorageSync('userList') || []
				const userIndex = userList.findIndex(item => item.uid === this.userInfo.uid)
				
				if (userIndex > -1) {
					userList[userIndex].cart = this.cartItems
					uni.setStorageSync('userList', userList)
					console.log('保存的购物车数据:', this.cartItems) // 调试日志
				} else {
					console.log('未找到用户数据') // 调试日志
				}
			} catch (error) {
				console.error('保存购物车数据失败:', error)
			}
		}
	},
	onLoad() {
		this.loadCartItems()
		this.loadUserInfo()
	},
	onShow() {
		this.loadCartItems()
		this.loadUserInfo()
	}
}
</script>

<style>
.cart-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: 220rpx;
	position: relative;
}

.empty-cart {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding-top: 200rpx;
}

.empty-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 30rpx;
}

.empty-text {
	color: #999;
	font-size: 28rpx;
	margin-bottom: 30rpx;
}

.go-shopping-btn {
	background-color: #007AFF;
	color: #fff;
	padding: 20rpx 60rpx;
	border-radius: 40rpx;
	font-size: 28rpx;
}

.cart-list {
	padding: 20rpx;
}

.cart-item {
	display: flex;
	align-items: center;
	background-color: #fff;
	padding: 20rpx;
	margin-bottom: 20rpx;
	border-radius: 12rpx;
}

.item-left {
	margin-right: 20rpx;
}

.item-content {
	flex: 1;
	display: flex;
	align-items: center;
}

.item-image {
	width: 160rpx;
	height: 160rpx;
	border-radius: 8rpx;
	margin-right: 20rpx;
}

.item-info {
	flex: 1;
}

.item-name {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
}

.item-price {
	font-size: 32rpx;
	color: #ff6b6b;
	font-weight: bold;
}

.item-right {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
}

.quantity-control {
	display: flex;
	align-items: center;
	margin-bottom: 10rpx;
}

.quantity-btn {
	width: 50rpx;
	height: 50rpx;
	border: 1px solid #ddd;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
}

.quantity {
	width: 60rpx;
	text-align: center;
	font-size: 28rpx;
}

.delete-btn {
	color: #999;
	font-size: 24rpx;
}

.cart-footer {
	position: fixed;
	bottom: 100rpx;
	left: 0;
	right: 0;
	height: 100rpx;
	background-color: #fff;
	display: flex;
	align-items: center;
	padding: 0 20rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	z-index: 999;
	width: 100%;
	box-sizing: border-box;
}

.footer-left {
	display: flex;
	align-items: center;
	min-width: 120rpx;
}

.footer-left text {
	margin-left: 10rpx;
	font-size: 28rpx;
	color: #333;
}

.footer-right {
	flex: 1;
	display: flex;
	justify-content: flex-end;
	align-items: center;
	margin-left: 20rpx;
}

.total-info {
	margin-right: 20rpx;
	display: flex;
	align-items: center;
}

.total-price {
	color: #ff6b6b;
	font-size: 32rpx;
	font-weight: bold;
	margin-left: 10rpx;
}

.checkout-button {
	background-color: #007AFF;
	color: #fff;
	padding: 0 40rpx;
	height: 70rpx;
	line-height: 70rpx;
	border-radius: 35rpx;
	font-size: 28rpx;
	min-width: 180rpx;
	text-align: center;
}

.checkout-button[disabled] {
	background-color: #ccc;
}
</style>